<template>
  <el-card>
    <div style="margin-bottom: 20px;">
      <el-switch
        v-model="isEdit"
        size="large"
        active-text="编辑"
        inactive-text="添加"
      />
    </div>
    <div style="margin-bottom: 20px;">
      <el-button type="primary" @click="handleSubmit">提交</el-button>
      <el-button @click="handleReset">重置</el-button>
    </div>
    <BaseForm ref="formRef" label-width="100px" :item-span="6" :form-list="columns" :model="formData">
    </BaseForm>
    <div style="margin-top: 18px">
    </div>
  </el-card>
</template>

<script lang="ts">
export default {
  name: "BaseFormDemo",
};
</script>
<script setup lang="ts">
import { getUserList } from "@/api/user";

const getTableList = (params: any) => {
  let newParams = JSON.parse(JSON.stringify(params));
  newParams.createTime && (newParams.startTime = newParams.createTime[0]);
  newParams.createTime && (newParams.endTime = newParams.createTime[1]);
  delete newParams.createTime;
  return getUserList(newParams).then((res: any) => {
    res.data?.list.map((item: any) => {
      item.age = item.user.detail.age
    })
    return res.data
  });
};

// 动态表单
const columns = ref([
  {
    prop: "username",
    label: "用户姓名",
    valueType: "input",
    rules: [
    { required: true, message: '用户姓名', trigger: 'blur' },
    ]
  },
  {
    prop: "gender",
    label: "性别",
    // 字典数据
    options: [
      {
        label: "女", value: 1
      },
      {
        label: "男", value: 2
      },
    ],
    valueType: "select",
  },
  {
    prop: "age",
    label: "年龄",
    valueType: "input-number",
  },
  {
    prop: "idCard",
    label: "身份证号",
    valueType: "input",
  },
  { 
    prop: "email", 
    label: "邮箱",
    valueType: "input",
  },
  {
    prop: "address",
    label: "居住地址",
    valueType: "input",
  },
  {
    prop: "status",
    label: "用户状态",
    options: [
      { label: "禁用", value: 0 },
      { label: "启用", value: 1 },
    ],
    valueType: "select",
  },
])

const isEdit = ref(false)

const formRef = ref()

const formData = ref({})

const handleReset = () => {
  formRef.value.resetFields()
};

const handleSubmit = () => {
  const data = formRef.value.getData();
  console.log("data: ", data);
  formRef.value.validate((valid: boolean) => {
    if (valid) {
      console.log('valid: ', valid);
    }
  })
};

const getItemData = () => {
  const params = { pageNum: 1, pageSize: 1 }
  getTableList(params).then((res: any) => {
    const { list } = res
    formData.value = list[0]
  });
};

watch(
  isEdit,
  (newVal) => {
    handleReset()
    if (newVal) {
      getItemData()
    } else {
      formData.value = {}
    }
  }
)
</script>

<style scoped>
.table-header {
  margin-bottom: 10px;
}
</style>